package com.car.rental.order.service.impl;

import com.car.rental.common.core.exception.BusinessException;
import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.order.dto.RentalExtensionDTO;
import com.car.rental.order.dto.EarlyReturnDTO;
import com.car.rental.order.entity.RentalOrder;
import com.car.rental.order.enums.OrderStatus;
import com.car.rental.order.service.RentalPeriodService;
import com.car.rental.order.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class RentalPeriodServiceImpl implements RentalPeriodService {

    private final OrderServiceImpl orderService;
    private final MessageService messageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> extendRental(Long userId, RentalExtensionDTO extensionDTO) {
        // 1. 查询订单
        RentalOrder order = orderService.getByOrderNo(userId, extensionDTO.getOrderNo());
        
        // 2. 检查订单状态
        if (order.getStatus() != OrderStatus.IN_USE.getCode()) {
            throw new BusinessException("当前订单状态不允许续租");
        }
        
        // 3. 检查新的结束时间
        if (extensionDTO.getNewEndTime().isBefore(order.getEndTime())) {
            throw new BusinessException("新的结束时间不能早于原结束时间");
        }
        
        // 4. 计算续租费用
        BigDecimal dailyPrice = new BigDecimal("100"); // 这里需要从车辆服务获取
        long extraDays = Duration.between(order.getEndTime(), extensionDTO.getNewEndTime()).toDays() + 1;
        BigDecimal extraAmount = dailyPrice.multiply(new BigDecimal(extraDays));
        
        // 5. 更新订单
        order.setEndTime(extensionDTO.getNewEndTime());
        order.setTotalAmount(order.getTotalAmount().add(extraAmount));
        orderService.updateById(order);
        
        // 6. 发送续租消息
        messageService.sendRentalReminderMessage(extensionDTO.getOrderNo());
        
        return ResponseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> earlyReturn(Long userId, EarlyReturnDTO returnDTO) {
        // 1. 查询订单
        RentalOrder order = orderService.getByOrderNo(userId, returnDTO.getOrderNo());
        
        // 2. 检查订单状态
        if (order.getStatus() != OrderStatus.IN_USE.getCode()) {
            throw new BusinessException("当前订单状态不允许提前还车");
        }
        
        // 3. 检查还车时间
        if (returnDTO.getActualReturnTime().isAfter(order.getEndTime())) {
            throw new BusinessException("实际还车时间不能晚于预定结束时间");
        }
        
        // 4. 计算退款金额（如果需要）
        // 这里可以根据业务规则计算退款金额
        
        // 5. 更新订单
        order.setEndTime(returnDTO.getActualReturnTime());
        order.setStatus(OrderStatus.COMPLETED.getCode());
        orderService.updateById(order);
        
        // 6. 发送提前还车消息
        messageService.sendRentalReminderMessage(returnDTO.getOrderNo());
        
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<Boolean> checkOvertime(String orderNo) {
        RentalOrder order = orderService.getById(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        boolean isOvertime = false;
        if (order.getStatus() == OrderStatus.IN_USE.getCode()) {
            isOvertime = LocalDateTime.now().isAfter(order.getEndTime());
        }
        
        return ResponseResult.success(isOvertime);
    }

    @Override
    public void sendRentalReminder(String orderNo) {
        RentalOrder order = orderService.getById(orderNo);
        if (order == null || order.getStatus() != OrderStatus.IN_USE.getCode()) {
            return;
        }
        
        // 计算距离结束还有多少时间
        Duration duration = Duration.between(LocalDateTime.now(), order.getEndTime());
        long hours = duration.toHours();
        
        // 发送不同类型的提醒
        if (hours <= 24) {
            // 发送24小时提醒
            messageService.sendRentalReminderMessage(orderNo);
        } else if (hours <= 48) {
            // 发送48小时提醒
            messageService.sendRentalReminderMessage(orderNo);
        }
    }
} 